/**
 * 工位管理
 */
import React, { useState, useEffect, useCallback } from 'react';
import { Table, Form, Input, Button, Modal, message, Tooltip, Icon } from 'antd';
import { history } from 'umi'
import { isArray } from 'lodash';
import { PageContainer } from '@/molecules';
import { Pagination, TableFilter } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import AuthComponent from '@/utils/auth/AuthComponent';
import { Operates } from '@/pages/Recruitment/components';
import { Company } from '@/containers';

import { getStationList, getSiteSelectList, handleBatchUnRelativeEmployee, getAreaSelect } from '../service';
import styles from '../index.less';
import { OperateRelative, OperateDeleteStation, OperateRemoveStation } from '../Components';

import { STATION_STATUS } from './enum';

function Station({ form, location }) {
    const { query = {} } = location;
    const { setFieldsValue } = form;
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [batchUnLinkData, setBatchUnLinkData] = useState({});
    const { data = {}, loading, run } = useRequest(getStationList, {
        manual: true,
        ...defaultFormatResult
    });

    const { data: siteData = [] } = useRequest(getSiteSelectList, {
        ...defaultFormatResult
    });

    const { data: areaData = [] } = useRequest(getAreaSelect, {
        ...defaultFormatResult
    });
    const siteList =
        siteData?.map(item => ({
            text: item.addressName,
            value: item.addressCode
        })) || [];

    const areaList = areaData?.map(item => ({
        text: item,
        value: item
    }));
    const dataSource =
        data?.rows ||
        [
            // {
            //     id: 1,
            //     addressName: '中航紫金',
            //     cubicleAreaCode: 'xxxx',
            //     cubicleStatus: 0,
            //     organizationName: '厦门微微',
            //     employeeName: '王老大'
            // }
        ];
    const total = data?.total || 0;
    const getParams = key => {
        if (query[key]) {
            return isArray(query[key]) ? query[key] : [query[key]];
        }
        return [];
    };
    // 刷新
    const handleRefresh = useCallback(() => {
        setSelectedRowKeys([]);
        setBatchUnLinkData({});
        run({
            ...query,
            addressCodes: getParams('addressCodes'),
            cubicleAreas: getParams('cubicleAreas'),
            cubicleStatus: getParams('cubicleStatus')
        });
    }, [run, query]);

    useEffect(() => {
        handleRefresh();
    }, [query]);

    const columns = [
        {
            title: '办公地点',
            dataIndex: 'addressCodes',
            filteredValue:
                query?.addressCodes && (isArray(query?.addressCodes) ? query?.addressCodes : [query?.addressCodes]),
            filters: siteList,
            render: (_, record) => record.addressName
        },
        {
            title: '工位编号',
            dataIndex: 'cubicleAreas',
            filteredValue:
                query?.cubicleAreas && (isArray(query?.cubicleAreas) ? query?.cubicleAreas : [query?.cubicleAreas]),
            filters: areaList,
            render: (_, record) => record.cubicleAreaCode
        },
        {
            title: '状态',
            dataIndex: 'cubicleStatus',
            filteredValue:
                query?.cubicleStatus && (isArray(query?.cubicleStatus) ? query?.cubicleStatus : [query?.cubicleStatus]),
            filters: STATION_STATUS,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: (text, record) => <span style={{ color: record.cubicleStatus === 0 ? '' : 'rgba(0,0,0,0.25)' }}>{STATION_STATUS.find(item => item.value === `${text}`)?.text}</span>
        },
        {
            title: '组织机构',
            dataIndex: 'organizationName',
            render: (text, record) => (text ? <Tooltip title={record.formatOrganizationName}>{text}</Tooltip> : '--')
        },
        {
            title: '员工姓名',
            dataIndex: 'employeeName',
            render: text => text || '--'
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 180,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (_, record) => {
                const operates =
                    record.cubicleStatus === 0
                        ? [
                            <OperateRelative info={record} onRefresh={handleRefresh}/>,
                            <OperateDeleteStation info={record} onRefresh={handleRefresh}/>
                        ]
                        : [
                            <OperateRemoveStation
                                type="remove"
                                info={record}
                                siteList={siteList}
                                onRefresh={handleRefresh}
                            />,
                            <OperateRemoveStation
                                type="delete"
                                info={record}
                                siteList={siteList}
                                onRefresh={handleRefresh}
                            />
                        ];
                return <Operates operates={operates} />;
            }
        }
    ];

    const handleUnLink = () => {
        Modal.confirm({
            title: `确定批量解除该${batchUnLinkData?.ids?.length}个已关联员工吗？`,
            icon: <Icon style={{ color: '#F55656' }} type="close-circle" theme="filled" />,
            onOk: async () => {
                try {
                    const { code, msg } = await handleBatchUnRelativeEmployee(batchUnLinkData);
                    if (code === 10000) {
                        message.success('批量解除成功！');
                    } else {
                        message.error(msg);
                    }
                    handleRefresh();
                } catch (e) {
                    console.log(e);
                }
            }
        });
    };
    const handleTableChange = (_, filters = {}) => {
        console.log(filters);
        const { addressCodes, cubicleStatus, cubicleAreas } = filters;
        history.replace({
            query: {
                ...query,
                addressCodes,
                cubicleAreas,
                cubicleStatus,
                pageNo: 1
            }
        });
    };

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.replace({ query: { ...query, pageNo: current, pageSize } });
    };

    const handleSubmit = e => {
        if (e) {
            e.preventDefault();
        }
        form.validateFields((err, values) => {
            if (!err) {
                history.replace({
                    query: {
                        ...query,
                        ...values,
                        pageNo: 1
                    }
                });
            }
        });
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: (keys, selectedRows) => {
            setSelectedRowKeys(keys);
            const ids = [];
            const cubicleEmployees = [];
            selectedRows.forEach(item => {
                const { id, employeeCode, employeeName } = item;
                ids.push(id);
                cubicleEmployees.push({
                    cubicleLinkEmployee: {
                        employeeCode,
                        employeeName
                    },
                    id
                });
            });
            setBatchUnLinkData({
                ids,
                cubicleEmployees
            });
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: record => ({
            disabled: record.cubicleStatus === 0
        })
    };
    return (
        <PageContainer>
            <header className={styles.headerWrapper}>
                <div className={styles.conditionWrapper}>
                    <Form layout="inline" autoComplete="off" onSubmit={handleSubmit} style={{ marginBottom: 0 }}>
                        <Form.Item>
                            {form.getFieldDecorator('extendText', { initialValue: query?.extendText })(
                                <Input.Search
                                    placeholder="搜索工位编号、办公地点、员工姓名"
                                    allowClear
                                    onSearch={value => {
                                        if (!value && !query.extendText) return;
                                        setFieldsValue({ extendText: value });
                                        handleSubmit();
                                    }}
                                    style={{ width: 306 }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="行政机构" style={{ marginRight: 8 }}>
                            {form.getFieldDecorator('companyCode', {
                                initialValue: query?.companyCode || undefined
                            })(
                                <Company
                                    onChange={val => {
                                        if (!val) {
                                            setFieldsValue({ companyCode: undefined });
                                            handleSubmit();
                                        }
                                    }}
                                    requestParams={{ status: 1 }}
                                    placeholder="请选择行政机构"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                />
                            )}
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                搜索
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
                <div className={styles.extendWrapper}>
                    <AuthComponent code="office:administration:adminManage:station:unLink">
                        <Button disabled={!selectedRowKeys.length} onClick={handleUnLink}>
                            批量解除
                        </Button>
                    </AuthComponent>
                    <AuthComponent code="office:administration:adminManage:stationAdd">
                        <Button
                            type="primary"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/institutions/adminManage/station/add'
                                });
                            }}
                        >
                            新增工位
                        </Button>
                    </AuthComponent>
                </div>
            </header>
            <Table
                rowKey="id"
                rowSelection={rowSelection}
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                onChange={handleTableChange}
                scroll={{ x: 'max-content' }}
                loading={loading}
            />
            <Pagination
                current={query.pageNo}
                pageSize={query.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
        </PageContainer>
    );
}

export default Form.create()(Station);
